package com.zingrow.web.user.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.ehcache.search.aggregator.Count;
import net.sf.json.JSONArray;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.idaycrm.idaybase.utils.JsonUtils;
import com.sun.tools.classfile.Annotation.element_value;
import com.zingrow.common.ReturnStandardDataFormat;
import com.zingrow.common.utils.CommonUtils;
import com.zingrow.common.utils.EncodingUtils;
import com.zingrow.common.utils.JsonHelper;
import com.zingrow.common.utils.MD5Util;
import com.zingrow.common.utils.NetworkUtil;
import com.zingrow.common.utils.OptClass;
import com.zingrow.common.utils.PageView;
import com.zingrow.common.utils.PatternUtil;
import com.zingrow.web.base.CodeMsg;
import com.zingrow.web.base.controller.BaseController;
import com.zingrow.web.base.enums.Menu;
import com.zingrow.web.base.enums.Operation;
import com.zingrow.web.base.enums.OperationDeed;
import com.zingrow.web.base.enums.OperationMinModule;
import com.zingrow.web.base.enums.OperationModule;
import com.zingrow.web.configure.iformation.service.IIformationService;
import com.zingrow.web.customer.model.Group;
import com.zingrow.web.customer.service.IGroupService;
import com.zingrow.web.push.bind.model.Bind;
import com.zingrow.web.push.bind.service.IBindService;
import com.zingrow.web.report.model.RptCycle;
import com.zingrow.web.report.service.ICycleService;

import com.zingrow.web.support.operate.model.OptRecord;
import com.zingrow.web.support.operate.service.IOptRecordService;
import com.zingrow.web.user.mapper.UserMapper;
import com.zingrow.web.user.mapper.UserPermissionMapper;
import com.zingrow.web.user.model.ActiveUser;
import com.zingrow.web.user.model.User;
import com.zingrow.web.user.model.Appupdate;
import com.zingrow.web.user.model.UserModelScheme;
import com.zingrow.web.user.model.UserPermission;
import com.zingrow.web.user.service.IAppupdateService;
import com.zingrow.web.user.service.IPermissionService;
import com.zingrow.web.user.service.IUserModelSchemeService;
import com.zingrow.web.user.service.IUserService;
import com.zingrow.web.user.service.impl.UserService;

/**
 * 用户管理控制层
 * 
 * @author sy
 *
 */
@Controller
@RequestMapping(value = "/user/", produces = "application/json;charset=UTF-8")
public class UserController extends BaseController {

	@Autowired
	private IUserService userService;
	@Autowired
	private IOptRecordService optRecordService;
	@Autowired
	private IBindService bindService;
	@Autowired
	private IUserModelSchemeService userModelSchemeService;
	@Autowired
	private UserPermissionMapper  userPermissionMapper;
	@Autowired
	private UserMapper UserMapper;
	@Autowired
	private IGroupService groupService;
	@Autowired
	private ICycleService cycleServiceImpl;
	@Autowired
	private IAppupdateService appupdateService;
	@Autowired
	private IPermissionService permissionService;
	@Autowired
	private IOptRecordService ioptRecordService;
	@Autowired
	private IIformationService iiformationService;

	//App跟新信息修改
		@ResponseBody
		@RequestMapping("Appupdate")
		public String Appupdate(HttpServletRequest request,HttpServletResponse response
				,String edition,String title,String whetherforce,String whetherdata,String pass) {
			ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);        
			try{
				if(pass.equals("848586"))
				{
				if (title != null || "".equals(title)) 
					title = EncodingUtils.fixUrlParamEncoding(request, title); 
				appupdateService.inappupdate(edition, title, whetherforce, whetherdata);
				}else{
				standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
				standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
		       } catch (Exception e) {
			log.error("更新信息错误");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		    }	
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		
		//获取APP跟新信息
		@ResponseBody
		@RequestMapping("Appupdates")
		public String Appupdates() {
			ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR,CodeMsg.MSG_ERROR,null);        
			try{
				Appupdate appupdate=appupdateService.outappupdate();
				standardData.setAppupdate_edition(appupdate.getAppupdate_edition());
				standardData.setAppupdate_title(appupdate.getAppupdate_title());
				standardData.setAppupdate_whetherdata(appupdate.getAppupdate_whetherdata());
				standardData.setAppupdate_whetherforce(appupdate.getAppupdate_whetherforce());
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
		       } catch (Exception e) {
			log.error("查询失败");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		    }   
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}
	/**
	 * 用户登出
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("logout")
	public String logout(HttpServletRequest request) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		// 在Session中清除userinfo
		NetworkUtil network=new NetworkUtil();
		try {
			//System.out.print(network.getIpAddress(request));
			String ip=network.getIpAddress(request);
			String op=network.getOsAndBrowserInfo(request);
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord us = new OptClass().user_login(opuser,Menu.Customerconfiguration.toString(),Menu.customer.toString(),Operation.userlog.toString(),ip,op);
			ioptRecordService.insert(us);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage("登出成功");		
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 修改账户密码
	 *
	 * @param httpRequest
	 * @param response
	 * @param userId
	 * @param pwd1
	 *            原密码
	 * @param pwd2
	 *            新密码
	 * @return
	 */
	@ResponseBody
	@RequestMapping("mpdifyPwd")
	public String mpdifyPwd(HttpServletRequest httpRequest, Integer userId, String pwd1, String pwd2) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {
			if (CommonUtils.isStrNull(pwd1) || CommonUtils.isStrNull(pwd2) || CommonUtils.isObjectNull(userId)) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (userService.queryByUserId(userId) == null
					|| !userService.queryByUserId(userId).getUserPwd().equals(MD5Util.MD5Encode(pwd1, null))) {
				// 检测原密码是否一致
				ActiveUser opuser = getUser(httpRequest);//获取操作用户
				OptRecord s = new OptClass().recordabnormality(opuser,"修改失败，原密码验证错误");
				ioptRecordService.insert(s);
				standardData.setReturnCode(CodeMsg.CODE_ERROR_OTHER);
				standardData.setReturnMessage("修改失败，原密码验证错误。");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			User user = new User();
			user.setUserId(userId);
			user.setUpdateTime(new Date());
			user.setUserPwd(pwd2);
			ActiveUser opuser = getUser(httpRequest);//获取操作用户
			// 进行修改操作
			if (userService.updateByPrimaryKey(user)) {
				// 操作成功
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);	
				if(opuser.getUserType()==2){
				addOptRecode(httpRequest, optRecordService, OperationModule.me.toString(),
		          		OperationMinModule.zhongzhou.toString(), "修改密码","");

			   } else
			   {
				    ActiveUser opusers = getUser(httpRequest);//获取操作用户
					OptRecord s = new OptClass().user_deletes(opusers,Menu.Customerconfiguration.toString(),Menu.customer.toString(),
							Operation.xiug.toString(),"自我修改当前登录用户密码!");
					ioptRecordService.insert(s);
			   }
			}else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("修改账户密码异常");
			log.error(e.getMessage());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 这个方法用于登录超时的处理
	 *
	 * @param request
	 * @param response
	 * @param bodyContent
	 * @return
	 */
	@ResponseBody
	@RequestMapping("sessionTimeoutWeb")
	public String sessionTimeoutWeb(HttpServletRequest request, HttpServletResponse response,
			@RequestBody String bodyContent) {
		// 返回登陆超时信息
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_LOHIN_TIMEOUT,
				CodeMsg.MSG_LOHIN_TIMEOUT, getWebBasePath(request) + "login/login.jsp");

		standardData.setBasePath(getWebBasePath(request));
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 根据用户名,账号，电话，邮箱和类型查询账户信息
	 *
	 * @param httpRequest
	 * @param response
	 * @param pageIndex
	 * @param pageSize
	 * @param account
	 * @param userType
	 * @param name
	 * @param mailbox
	 * @return
	 */
	@ResponseBody
	@RequestMapping("queryByParams")
	public String queryByParams(HttpServletRequest httpRequest, HttpServletResponse response, Integer pageIndex,
			Integer pageSize, String account,String name,String phone,String mailbox, Integer userType, String group) {
		List<User> returnList = new ArrayList<>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				returnList);
		PageView pageView = null;
		/*
		 * if (CommonUtils.isObjectNull(userType)) { // 判断传入参数合法性
		 * standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
		 * standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS); return
		 * JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss"); }
		 */
		try {

			if (pageIndex == null || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (pageSize == null || pageSize <= 0) {
				pageSize = 10;
			}
			pageView = new PageView(pageSize, pageIndex);
			if (account != null || !"".equals(account)) {
				account = EncodingUtils.fixUrlParamEncoding(httpRequest, account);
			}
			if (phone != null || !"".equals(phone)) {
				phone = EncodingUtils.fixUrlParamEncoding(httpRequest, phone);
			}
			if (name != null || !"".equals(name)) {
				name = EncodingUtils.fixUrlParamEncoding(httpRequest, name);
			}
			if (mailbox != null || !"".equals(mailbox)) {
				mailbox = EncodingUtils.fixUrlParamEncoding(httpRequest, mailbox);
			}
			returnList = userService.queryByParams(pageView, account, userType, group,name,phone,mailbox);
		} catch (Exception e) {
			log.error("根据参数查询用户异常");
			log.error(e, e.fillInStackTrace());
			ActiveUser opuser = getUser(httpRequest);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"根据参数查询用户异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(returnList);
		}
		// 操作日志记录
		ActiveUser opuser = getUser(httpRequest);//获取操作用户
		String groupname="";
		if(StringUtils.isNoneBlank(group))
		groupname=groupService.selectGroupNameByGroupid(Integer.parseInt(group));
		OptRecord s = new OptClass().user_query(opuser,Menu.Customerconfiguration.toString(),Menu.customer.toString(),Operation.query.toString(),account,name,phone,mailbox,groupname);
		if(s.getOptName()!="null")
		ioptRecordService.insert(s);
		// 执行到这代表查询成功
		standardData.setReturnData(returnList);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		standardData.setTotalPages(pageView.getPageCount());
		standardData.setTotalRecords(pageView.getRowCount());
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 根据用户名和类型查询账户信息 只查询超级管理员和普通管理用户
	 * 
	 * @param httpRequest
	 * @param response
	 * @param pageIndex
	 * @param pageSize
	 * @param account
	 * @return
	 */
	@ResponseBody
	@RequestMapping("queryParams")
	public String queryParams(HttpServletRequest httpRequest, HttpServletResponse response, Integer pageIndex,
			Integer pageSize, String account) {
		List<User> returnList = new ArrayList<>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				returnList);
		PageView pageView = null;
		try {
			if (pageIndex == null || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (pageSize == null || pageSize <= 0) {
				pageSize = 10;
			}
			pageView = new PageView(pageSize, pageIndex);
			if (account != null || !"".equals(account)) {
				account = EncodingUtils.fixUrlParamEncoding(httpRequest, account);
			}
			returnList = userService.queryParams(pageView, account);
		} catch (Exception e) {
			log.error("根据参数查询用户异常");
			log.error(e, e.fillInStackTrace());
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(returnList);
		}
		// 执行到这代表查询成功
		standardData.setReturnData(returnList);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		standardData.setTotalPages(pageView.getPageCount());
		standardData.setTotalRecords(pageView.getRowCount());
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 删除一个帐号信息(仅仅改变is_delete)
	 *
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("deleteUser")
	public String deleteUser(HttpServletRequest httpRequest, Integer userId, String userName, Integer userType) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {
			if (CommonUtils.isObjectNull(userId)) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (userService.deleteUser(userId)) {
				if (userType == 2) {
					// 处理session
					DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils
							.getSecurityManager();
					DefaultWebSessionManager sessionManager = (DefaultWebSessionManager) securityManager
							.getSessionManager();
					// 获取当前已登录的用户session列表
					Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();
					// 处于会话过程中的用户
					ActiveUser loginedUser = null;
					for (Session session2 : sessions) {
						if (session2.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) != null) {
							// 获取之前处于会话过程中的用户信息
							loginedUser = (ActiveUser) ((SimplePrincipalCollection) session2
									.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal();
							// 此次登录用户与之前会话用户为同一用户
							if (userId.equals(loginedUser.getUserId())) {
								// sessionManager.getSessionDAO().delete(session2);
								session2.setAttribute("isRemove", "1");
							}
						}

					}
				} else {
				}
				if(userType != 1)
				{
				ActiveUser opuser = getUser(httpRequest);//获取操作用户
				OptRecord s = new OptClass().user_delete(opuser,Menu.Customerconfiguration.toString(),Menu.customer.toString(),Operation.delete.toString(),userName);
				ioptRecordService.insert(s);
				}
				// 操作成功
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("删除账户信息异常");
			ActiveUser opuser = getUser(httpRequest);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"删除账户信息异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	// -------------------------
	/**
	 * 用户登录
	 * 
	 * @param user
	 *            登录用户
	 * @return
	 */
	// TODO 改进改进
	@RequestMapping("login")
	@ResponseBody
	public String login(String account, String password, HttpSession session, HttpServletRequest request,
			String appChannelId, Integer appType, Integer versionNumber,String phoneType,String phoneSystem,String loginType) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		// System.out.println(session.getId().toString());
		// 获取当前的Subject(shiro下认为的当前操作用户对象)
		Subject currentUser = SecurityUtils.getSubject();
		account = account.replaceAll(" ", "").replaceAll(" ", "");
		account = account.toLowerCase();
		UsernamePasswordToken token = new UsernamePasswordToken(account, password);
		token.setRememberMe(false);

		String loginSource = request.getParameter("loginSource");
		String sessionID = "";
		try {
			// 对用户进行认证
			currentUser.login(token);
		} catch (AuthenticationException e) {
			// 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
			log.error("用户名或密码错误,请检查后重新登录");
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage("用户名或密码错误,请检查后重新登录");
			return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
		}

		ActiveUser activeUser = (ActiveUser) currentUser.getPrincipal();
		// 认证通过
		if (currentUser.isAuthenticated()) {
			User GroupImage = UserMapper.queryGroupByUserName(account);
			//获取url
			String pathRoot=request.getRequestURL().toString();
			String temp[]=pathRoot.split("HandleAdmin");
			String pathRoot1=temp[0];
			try {
				// 拥有组织ID，通过组织ID查询所在组织
				//地址格式http://localhost:8080/HandleAdmin/images/DefaultAvatar.png
				//或http://localhost:8080/imageDir/Picture//***.png
				User GroupImage1 = UserMapper.selectGroupImage(GroupImage.getGroupId());
				String su=GroupImage1.getGroupImage();
                if(su.equals(null)||su.equals(""))
                {
                	activeUser.setGroupimage(pathRoot1+"HandleAdmin/images/DefaultAvatar.png");
                	activeUser.setGroupname("中周信息");
                }
                else
                {
                	activeUser.setGroupimage(pathRoot1+"imageDir/"+GroupImage1.getGroupImage());
                	activeUser.setGroupname(GroupImage1.getGroupName());
                }
                //根据用户ID 查询用户拥有哪些报告类型
                List<RptCycle> list = cycleServiceImpl.selectByUserId(GroupImage.getUserId());
                //结果集返回给手机APP
                activeUser.setCyclelist(list);
			} catch (Exception e) {
				// 未拥有组织ID用户传入默认图片
				activeUser.setGroupimage(pathRoot1+"HandleAdmin/images/DefaultAvatar.png");
				activeUser.setGroupname("中周信息");
			}
			//获取用户用户名
			User s=UserMapper.selectByAccount(account);
			if(s!=null)
			{
            activeUser.setUserName(s.getUserName());
			}
			// 获取请求的sessionID
			sessionID = session.getId().toString();
			// 当前用户Session
			Session thisSession = null;
			// 处理session
			DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
			DefaultWebSessionManager sessionManager = (DefaultWebSessionManager) securityManager.getSessionManager();
			// 获取当前已登录的用户session列表
			Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();
			// 本地Session集合
			List<Session> nativeSession = new ArrayList<>();
			// 处于会话过程中的用户
			ActiveUser loginedUser = null;
			for (Session session2 : sessions) {
				if (session2.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) != null) {
					// 获取之前处于会话过程中的用户信息
					loginedUser = (ActiveUser) ((SimplePrincipalCollection) session2
							.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)).getPrimaryPrincipal();
					// 此次登录用户与之前会话用户为同一用户
					if (token.getUsername().equals(loginedUser.getUserAccount())) {
						// 用户在不同设备上登录
						if (session2.getAttribute("sessionID") != null
								&& !sessionID.equals(session2.getAttribute("sessionID").toString())) {
							// 将新设备保存到本地Session集
							nativeSession.add(session2);
						} else {
							// 并非不同设备登录，将直接赋值给thisSession
							thisSession = session2;
						}
					}
				}

			}
			// 判段后台设置的用户登录状态是否为单设备登录（默认：1为单设备登录）
			if (activeUser.getSingleLogin() == 1) {
				if (activeUser.getUserType() == 1 || activeUser.getUserType() == 0) {
					// 清除该用户以前登录时保存的session
					for (Session session3 : nativeSession) {
						// session3.setAttribute("isweb", "1");
						sessionManager.getSessionDAO().delete(session3);
					}
				} else if (activeUser.getUserType() == 2 || activeUser.getUserType() == 23) {
					// 清除该用户以前登录时保存的session
					for (Session session3 : nativeSession) {
						session3.setAttribute("isReplace", "1");
						// sessionManager.getSessionDAO().delete(session3);
					}
				}
			}
			// 储存当前用户sessionID
			thisSession.setAttribute("sessionID", sessionID);
			if ("web".equals(loginSource)) {// web端登陆，客户账号不能登陆
				if (activeUser.getUserType() == 2) {
					standardData.setReturnMessage("您是客户帐号，不能登录管理系统！");
					return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
				} else if (activeUser.getUserType() == 3) {
					standardData.setReturnMessage("您是Web帐号，不能登录管理系统！");
					return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
				} else if (activeUser.getUserType() == 23) {
					standardData.setReturnMessage("您是客户和Web帐号，不能登录管理系统！");
					return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
				}
			} else {
				if (activeUser.getUserType() == null || activeUser.getUserType() == 0
						|| activeUser.getUserType() == 1) {
					standardData.setReturnMessage("您是内部用户，不能登陆到APP！");
					return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
				}
				if (activeUser.getUserType() == 3) {
					standardData.setReturnMessage("您是Web账号，不能登陆到APP！");
					return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
				} else {
					// 这里将手机用户的相关信息保存到用户手机绑定表
					// 保存之前先查看表中是否存在此手机的绑定信息（baidu_channel_id是否存在）
					// 不存在的情况下绑定此手机
					// 调用接口查询用户的组织信息
					// 绑定手机
					// 查看表中是否存在此手机绑定的信息与登录的用户账号是否一致
					// 不一致说明此手机为其他用户登录，则修改此手机的绑定用户信息
					if(StringUtils.isNoneBlank(appChannelId)){
						bindService.deleteBindByChannelId(appChannelId);
					}
					if (!bindService.selectSameBybaidu_channel_id(null, account)) {
						User user = userService.queryGroupByUserName(account);
						Bind bind = new Bind();
						bind.setUser_account(account);
						bind.setGroup_id(user.getGroupId());
						bind.setBaidu_app_type(appType);
						if (appType == 3) {
							bind.setBaidu_app_id("8389244");
						} else if (appType == 4) {
							bind.setBaidu_app_id("7938505");
						}
						bind.setBaidu_channel_id(appChannelId);
						bind.setBinding_date(new Date());
						bind.setBadge(0);
						bind.setVersionNumber(versionNumber != null ? versionNumber : 0);
						bindService.insert(bind);
					}
					// 现在改成不管是不是其他用户登录，都修改此手机绑定的用户信息，因为改需求说只推送用户最新登录的手机所以修改登录时间
					else {
						User user = userService.queryGroupByUserName(account);
						Bind bind = new Bind();
						bind.setUser_account(account);
						bind.setGroup_id(user.getGroupId());
						bind.setBaidu_app_type(appType);
						if (appType == 3) {
							bind.setBaidu_app_id("8389244");
						} else if (appType == 4) {
							bind.setBaidu_app_id("7938505");
						}
						bind.setBadge(0);
						bind.setBaidu_channel_id(appChannelId);
						bind.setBinding_date(new Date());
						bind.setVersionNumber(versionNumber != null ? versionNumber : 0);
						// 修改
						bindService.modify(bind);
					}

				}
			}

			if("web".equals(loginSource))
			{
			NetworkUtil network=new NetworkUtil();
			try {
				//System.out.print(network.getIpAddress(request));
				String ip=network.getIpAddress(request);
				String op=network.getOsAndBrowserInfo(request);
				ActiveUser opuser = getUser(request);//获取操作用户
				OptRecord us = new OptClass().user_login(opuser,Menu.Customerconfiguration.toString(),Menu.customer.toString(),Operation.userlogin.toString(),ip,op);
				ioptRecordService.insert(us);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			}
			else
			{
			//存入手机型号
			activeUser.setPhoneType(phoneType);
			//存入手机版本
			activeUser.setPhoneSystem(phoneSystem);
			//判断是否是app用户登录
			if(activeUser.getUserType()==2){
				//自主登录
				if(StringUtils.isNotBlank(loginType)){
				if(loginType.equals("0")){
					addOptRecode(request, optRecordService, OperationModule.me.toString(), OperationMinModule.zhongzhou.toString(), OperationDeed.login.toString(), "");
				}
				//过期登录
				else if(loginType.equals("1")){
					addOptRecode(request, optRecordService, OperationModule.me.toString(), OperationMinModule.zhongzhou.toString(), OperationDeed.logins.toString(), "");
				}
				}
			}
			}

			standardData.setReturnCode(CodeMsg.CODE_OK);
			standardData.setReturnData(activeUser);
			standardData.setReturnMessage("登陆成功");
			session.setAttribute("userinfo", activeUser);
			session.setAttribute("UserId", activeUser.getUserId());
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
	/**
	 * 新增管理员用户
	 * */
	@RequestMapping("addAdminUser")
	@ResponseBody
	public String addAdminUser(User user, HttpServletRequest request){
			ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);		
		try {
			if (CommonUtils.isStrNull(user.getUserPwd()) || CommonUtils.isStrNull(user.getUserAccount())
					|| CommonUtils.isObjectNull(user.getUserType()) || user.getUserPwd().length() > 20
					|| user.getUserPwd().length() < 6 || user.getUserAccount().length() > 50) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			
			if(user.getUserPwd() != null){	
				
					user.setUserPwd(MD5Util.MD5Encode(user.getUserPwd(), null));	
			}
						
		    //默认开启
			user.setIsDelete(1);
			//邮箱默认为空
			user.setUserMailbox("");
			int i = 0;
			boolean b = false;
			b = userService.querySameByUserName(user.getUserAccount(), null, null);
			if (b) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("新增失败，已存在其他相同管理账户或APP账户！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			else{
			if(userService.addAdminUser(user)){
				/* if (user.getUserType() == 2) {
						addOptRecode(request, optRecordService, Menu.customer.toString(), Operation.insert.toString(),
								user.getUserAccount());
					} else if (user.getUserType() == 3) {
						addOptRecode(request, optRecordService, Menu.web.toString(), Operation.insert.toString(),
								user.getUserAccount());
					} else if (user.getUserType() == 23) {
						addOptRecode(request, optRecordService, Menu.customeWeb.toString(), Operation.insert.toString(),
								user.getUserAccount());
					} else {
						addOptRecode(request, optRecordService, Menu.user.toString(), Operation.insert.toString(),
								user.getUserAccount());
					}*/
				i = userPermissionMapper.addPro(userService.selectByUserAccount(user.getUserAccount()));
				// 操作成功
			} 
			if(i>0){
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage("新增" + CodeMsg.MSG_OK);
			}
			else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
			}
		 }
			catch (Exception e) {
				log.error("新增账户信息异常");
				log.error(e, e.fillInStackTrace());
				standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
				standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");		
	}
	/*
	 * 修改普通管理员用户
	 * 
	 * */
	@RequestMapping("modify2")
	@ResponseBody
	private String modify(User user, HttpServletRequest request) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {
			if (CommonUtils.isStrNull(user.getUserAccount()) || CommonUtils.isObjectNull(user.getUserId())
					|| user.getUserAccount().length() > 50) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (CommonUtils.isStrNotNull(user.getUserPwd())) {
				if (user.getUserPwd().length() > 20 || user.getUserPwd().length() < 6) {
					// 判断传入参数合法性
					standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
					standardData.setReturnMessage("密码长度错误！");
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}
			}			
			if (PatternUtil.isNotContain(user.getUserAccount())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("帐号只能数字和字母！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (user.getUserPwd() != null && !"".equals(user.getUserPwd())) {
				if (PatternUtil.isNotContain(user.getUserPwd())) {
					standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
					standardData.setReturnMessage("密码只能数字和字母！");
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}
			}
			if(user.getUserPwd() != null&&!"".equals(user.getUserPwd())){	
				
				user.setUserPwd(MD5Util.MD5Encode(user.getUserPwd(), null));	
		}
			boolean b = false;
			b = userService.querySameByUserName(user.getUserAccount(), user.getUserId(), null);
			if (b) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("修改失败，已存在其他相同管理账户或APP账户！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			else {
			if(userService.updateUserNameAndKey(user)){
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage("修改" + CodeMsg.MSG_OK);			
			}
			else{
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			}
		} catch (Exception e) {
			log.error("修改账户信息异常");
			log.error(e, e.fillInStackTrace());
			log.debug(e);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	
	/**
	 * 新增用户
	 */
	@RequestMapping("add")
	@ResponseBody
	public String add(User user, HttpServletRequest request) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {
			if (CommonUtils.isStrNull(user.getUserPwd()) || CommonUtils.isStrNull(user.getUserAccount())
					|| CommonUtils.isObjectNull(user.getUserType()) || user.getUserPwd().length() > 20
					|| user.getUserPwd().length() < 6 || user.getUserAccount().length() > 50) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			user.setUserAccount(user.getUserAccount().toLowerCase().replaceAll(" | ", ""));
			
			if (PatternUtil.isChinese(user.getUserName())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("用户名只能中文或英文！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			
			if (!PatternUtil.isNumberPhone(user.getUserPhone())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("这不是一个电话号码！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
				
			if (PatternUtil.isNotContain(user.getUserAccount())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("帐号只能数字和字母！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}

			if (PatternUtil.isNotContain(user.getUserPwd())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("密码只能数字和字母！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (!PatternUtil.isMailbox(user.getUserMailbox())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("邮箱格式错误！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			
			boolean b = false;
			boolean e = false;
			boolean f = false;
			boolean g = false;
			
			// 默认单设备登录
			if (CommonUtils.isObjectNull(user.getSingleLogin())) {
				user.setSingleLogin(1);
			}
			if (user.getUserType() == 2 || user.getUserType() == 23 || user.getUserType() == 3) {
				if (CommonUtils.isObjectNull(user.getGroupId())) {
					// 判断传入参数合法性
					standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
					standardData.setReturnMessage("组织不能为空");
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}
				// 根据组织ID查询组织信息
				Group group = groupService.selectgroupName(user.getGroupId());
				// 统计该组织下的用户数
				int count = userService.selectByGroupId(user.getGroupId());
				if (count >= group.getUserNum()) {
					standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
					standardData
							.setReturnMessage("[" + group.getGroupName() + "] 组织只能拥有  [" + group.getUserNum() + "]个用户");
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}
				b = userService.querySameByUserName(user.getUserAccount(), null, null);
				//e = userService.querySameByUserNameone(user.getUserName(), null,null);
				f = userService.querySameByUserPhone(user.getUserPhone(), null, null);
				g = userService.querySameByUserMailbox(user.getUserMailbox(),null,null);
			} else {
				b = userService.querySameByUserName(user.getUserAccount(), null, null);
				//e = userService.querySameByUserNameone(user.getUserName(), null,null);
				f = userService.querySameByUserPhone(user.getUserPhone(), null, null);
				g = userService.querySameByUserMailbox(user.getUserMailbox(),null,null);
			}
			if (b) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("新增失败，已存在其他相同管理账户或APP账户！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			/*if (e) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("修改失败，该用户名已存在！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}*/
			if (f) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("修改失败，该电话已存在！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (g) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("修改失败，该邮箱已存在！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}

			user.setInsertTime(new Date());

			if (userService.addUser(user)) {
				// 操作日志记录
				ActiveUser opuser = getUser(request);//获取操作用户
				String groupname=groupService.selectGroupNameByGroupid(user.getGroupId());
				OptRecord s = new OptClass().user_add(groupname,user,opuser,Menu.Customerconfiguration.toString(),Menu.customer.toString(),Operation.insert.toString());
				ioptRecordService.insert(s);
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage("新增" + CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("新增账户信息异常");
			//log.error(e, e.fillInStackTrace());
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"新增账户信息异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 修改用户
	 */
	@RequestMapping("modify")
	@ResponseBody
	private String modify(User user, HttpServletRequest request, Integer groupId2) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		try {
			//获取未修改时的用户信息
			User Originaluser=userService.queryByUserId(user.getUserId());
			if (CommonUtils.isStrNull(user.getUserAccount()) || CommonUtils.isObjectNull(user.getUserId())
					|| user.getUserAccount().length() > 50) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR_PARAMS);
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			//作为url进行编码
			user.setUserName(URLDecoder.decode(user.getUserName(),"utf8"));
			user.setUserAccount(user.getUserAccount().toLowerCase().replaceAll(" | ", ""));
			if (CommonUtils.isStrNotNull(user.getUserPwd())) {
				if (user.getUserPwd().length() > 20 || user.getUserPwd().length() < 6) {
					// 判断传入参数合法性
					standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
					standardData.setReturnMessage("密码长度错误！");
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}
			}
			if (PatternUtil.isChinese(user.getUserName())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("用户名只能中文或英文！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			
			if (!PatternUtil.isNumberPhone(user.getUserPhone())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("这不是一个电话号码！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
				
			if (PatternUtil.isNotContain(user.getUserAccount())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("帐号只能数字和字母！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (user.getUserPwd() != null && !"".equals(user.getUserPwd())) {
				if (PatternUtil.isNotContain(user.getUserPwd())) {
					standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
					standardData.setReturnMessage("密码只能数字和字母！");
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}
			}
			if (!PatternUtil.isMailbox(user.getUserMailbox())) {
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("邮箱格式错误！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			
			boolean b = false;
			boolean e = false;
			boolean f = false;
			boolean g = false;

			if (user.getUserType() != null && user.getUserType() == 2 || user.getUserType() == 3
					|| user.getUserType() == 23) {
				if (CommonUtils.isObjectNull(user.getGroupId())) {
					// 判断传入参数合法性
					standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
					standardData.setReturnMessage("组织不能为空");
					return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
				}

				// 默认单设备登录
				if (CommonUtils.isObjectNull(user.getSingleLogin())) {
					user.setSingleLogin(1);
				}
				b = userService.querySameByUserName(user.getUserAccount(), user.getUserId(), user.getUserType());
				//e = userService.querySameByUserNameone(user.getUserName(), user.getUserId(), user.getUserType());
				f = userService.querySameByUserPhone(user.getUserPhone(), user.getUserId(), user.getUserType());
				g = userService.querySameByUserMailbox(user.getUserMailbox(), user.getUserId(), user.getUserType());
			} else {
				b = userService.querySameByUserName(user.getUserAccount(), user.getUserId(), 1);
				//e = userService.querySameByUserNameone(user.getUserName(), user.getUserId(), 1);
				f = userService.querySameByUserPhone(user.getUserPhone(), user.getUserId(), 1);
				g = userService.querySameByUserMailbox(user.getUserMailbox(), user.getUserId(), 1);
			}
		
			if (b) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("修改失败，该账号已存在！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			/*if (e) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("修改失败，该用户名已存在！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}*/
			if (f) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("修改失败，该电话已存在！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (g) {
				// 检测到有除此信息之外的同名数据
				standardData.setReturnCode(CodeMsg.CODE_ERROR_SAME);
				standardData.setReturnMessage("修改失败，该邮箱已存在！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (userService.updateByPrimaryKey(user)) {
				// 判断用户所属组织是否修改，修改删除用户拥有的方案
				if (groupId2 != null && user.getGroupId() != null) {
					if (!groupId2.equals(user.getGroupId())) {
						//删除用户所有的方案
						userService.updateifmId(null, user.getUserId());
						//删除用户所有的报告
						userModelSchemeService.delete(user.getUserId());
					}
				}
				// 操作成功
				// 操作日志记录
				String groupname=groupService.selectGroupNameByGroupid(user.getGroupId());
				String Originaluergroupname=groupService.selectGroupNameByGroupid(Originaluser.getGroupId());
				user.setGroupName(groupname);
				Originaluser.setGroupName(Originaluergroupname);
				ActiveUser opuser = getUser(request);//获取操作用户		
				OptRecord s = new OptClass().user_update(user,Originaluser,opuser,Menu.Customerconfiguration.toString(),Menu.customer.toString(),Operation.update.toString());
				if(s.getOptName()!=null)
				ioptRecordService.insert(s);
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}
		} catch (Exception e) {
			log.error("修改账户信息异常");
			//log.error(e, e.fillInStackTrace());
			log.debug(e);
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"修改账户信息异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 改变用户权限
	 */
	@RequestMapping("modifyUserPro")
	@ResponseBody
	private String modifyUserPro(HttpServletRequest request, Integer userId, String ropeProgramme, String permission,
			Integer userType, String userAccount) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);

		try {
		
			if (CommonUtils.isObjectNull(userId)) {
				// 判断传入参数合法性
				standardData.setReturnCode(CodeMsg.CODE_ERROR_PARAMS);
				standardData.setReturnMessage("用户ID不能为空！");
				return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			if (userId == 1) {
				standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
				standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
				standardData.setReturnMessage("不能修改超级管理员权限！");
				return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			UserPermission uo=permissionService.selectbyid(userId);//根据用户账号获取所拥有方案权限
			if (userService.updateByUserIDPro(userId, ropeProgramme, permission)) {
				//操作日志记录
				ActiveUser opuser = getUser(request);//获取操作用户
				List<List<String>> list=new ArrayList<List<String>>();
			/*	String[] startlist= new String[50];
				if(uo!=null)
				startlist=uo.getRopeProgramme().split(",");	
				String[] endlist=ropeProgramme.split(",");
				List<List<String>> list=new OptClass().comparearray(startlist,endlist);
				for(int i=0;i<2;i++){	
				List<String> s=new ArrayList<String>();
				if(i==0&&list.get(0).size()==0){list.add(s);continue;}
				if(i==1&&list.get(1).size()==0){list.add(s);continue;}
				List<Iformation> iformationlist=iiformationService.selectlistId(list.get(i));
				for(int k=0;k<iformationlist.size();k++)s.add(iformationlist.get(k).getIfm_name()+"("+iformationlist.get(k).getIfm_note()+")");
	            list.add(s);}
	            */
			if(userType!=1)
			{
				OptRecord s = new OptClass().user_queryinformation(opuser,Menu.Customerconfiguration.toString(),Menu.customer.toString(),Operation.updateProinformation.toString(),userAccount,list);
				if(s.getOptName()!=null)
				ioptRecordService.insert(s);	
			}
				// 操作成功
				standardData.setReturnCode(CodeMsg.CODE_OK);
				standardData.setReturnMessage(CodeMsg.MSG_OK);
			} else {
				standardData.setReturnCode(CodeMsg.CODE_ERROR);
				standardData.setReturnMessage(CodeMsg.MSG_ERROR);
			}

		} catch (Exception e) {
			log.error("修改账户权限异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"修改账户权限异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");

	}

	/**
	 * 查看用户菜单信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("queryByUserMenus")
	@ResponseBody
	public String queryByUserMenus(HttpServletRequest request) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		ActiveUser user = getUser(request);
		if (user == null) {
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnMessage("请先登录！");
			return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		standardData.setReturnData(user);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 查看用户菜单信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("selByUserMenus")
	@ResponseBody
	public String selByUserMenus(HttpServletRequest request, Integer userId) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
        
		if (CommonUtils.isObjectNull(userId)) {
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnMessage("参数为空！");
			return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		UserPermission user = userService.selectByUserPer(userId);
		if (user == null) {
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		standardData.setReturnData(user);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * IOS 用户登录过快导致appChannelId绑定失败 备用绑定方法
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("IOSBindApp")
	@ResponseBody
	public String IOSBindApp(String account, HttpServletRequest request, String appChannelId, Integer versionNumber) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);

		if (account != null || "".equals(account)) {
			account = EncodingUtils.fixUrlParamEncoding(request, account);
		}
		if (appChannelId != null || "".equals(appChannelId)) {
			appChannelId = EncodingUtils.fixUrlParamEncoding(request, appChannelId);
		}
		try {
			Bind bind = bindService.selectIOSByuserAccount(null, account);
			if (bind != null) {
				bind.setUser_account(account);
				bind.setBaidu_channel_id(appChannelId);
				bind.setVersionNumber(versionNumber != null ? versionNumber : 0);
				// 将appChannelId加入绑定
				bindService.modifyByAccount(bind);
			}
		} catch (Exception e) {
			standardData.setReturnCode(Integer.valueOf(10010));
			standardData.setReturnMessage("已绑定成功，无需重复绑定");
			return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * APP退出解除手机绑定（绑定表中记录删除）
	 * 
	 * @param account
	 * @param request
	 * @param appChannelId
	 * @return
	 */
	@RequestMapping("deleteBindByAccountAndChannelId")
	@ResponseBody
	public String deleteBindByAccountAndChannelId(String account, HttpServletRequest request, String appChannelId) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);

		if (account != null || "".equals(account)) {
			account = EncodingUtils.fixUrlParamEncoding(request, account);
		}
		if (appChannelId != null || "".equals(appChannelId)) {
			appChannelId = EncodingUtils.fixUrlParamEncoding(request, appChannelId);
		}
		try {
			bindService.deleteBindByAccountAndChannelId(appChannelId, account);
		} catch (Exception e) {
			standardData.setReturnCode(Integer.valueOf(10003));
			standardData.setReturnMessage("用户退出解除绑定失败");
			return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
		}
		 addOptRecode(request, optRecordService, OperationModule.me.toString(),
          		OperationMinModule.zhongzhou.toString(), "退出登录","");
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	// 根据组织ID查询用户
	@RequestMapping("selectByGroupId")
	@ResponseBody
	public String selectId(HttpServletRequest request, Integer groupId) {
		List<User> list = new ArrayList<User>();
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				list);
		try {
			if (CommonUtils.isObjectNull(groupId)) {
				standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
				standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
				standardData.setReturnMessage("参数为空！");
				return JsonHelper.encodeObject2Json(standardData, "yyyy-MM-dd HH:mm:ss");
			}
			list = userService.selectId(groupId);
		} catch (Exception e) {
			log.error("查询异常");
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
			standardData.setReturnData(list);
		}
		standardData.setReturnData(list);
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}

	// 用户管理编辑用户模板权限接口
	@RequestMapping("insert")
	@ResponseBody
	public String insert(HttpServletRequest request, @RequestBody Map<String, Object> map, Integer userId,String userAccount) {
		ReturnStandardDataFormat standardData = new ReturnStandardDataFormat(CodeMsg.CODE_ERROR, CodeMsg.MSG_ERROR,
				null);
		// 解析map中的json数组
		String str = map.get("list").toString();
		@SuppressWarnings("static-access")
		JSONArray JsonArray = new JSONArray().fromObject(str);
		// 强转集合
		@SuppressWarnings("unchecked")
		List<UserModelScheme> list = (List<UserModelScheme>) JSONArray.toCollection(JsonArray, UserModelScheme.class);
		try {
			List<UserModelScheme> uo=userModelSchemeService.selectid(userId);
			// 编辑用户报告模板权限，先删除用户报告模板数据
			if (userId != null) {
				if (userModelSchemeService.delete(userId)) {
					standardData.setReturnCode(CodeMsg.CODE_OK);
					standardData.setReturnMessage(CodeMsg.MSG_OK);
				}
			}
			if (list.size() > 0) {
				for (UserModelScheme userModel : list) {
					if (userModelSchemeService.insert(userModel)) {
						standardData.setReturnCode(CodeMsg.CODE_OK);
						standardData.setReturnMessage(CodeMsg.MSG_OK);
					} else {
						standardData.setReturnCode(CodeMsg.CODE_ERROR);
						standardData.setReturnMessage(CodeMsg.MSG_ERROR);
					}
				}
			}	
			//操作日志
			ActiveUser opuser = getUser(request);//获取操作用户
			String[] startlist= new String[4];
			if(uo!=null){			
				for(int i=0;i<uo.size();i++)
					startlist[i]=uo.get(i).getCycleId().toString();}
			String[] endlist= new String[4];
			for(int i=0;i<list.size();i++)
				endlist[i]=list.get(i).getCycleId().toString();
			List<List<String>> lists=new OptClass().comparearray(startlist,endlist);
			OptRecord s = new OptClass().user_queryPresentation(opuser,Menu.Customerconfiguration.toString(),Menu.customer.toString(),Operation.updatePresentation.toString(),userAccount,lists);
			if(s.getOptName()!=null)
			ioptRecordService.insert(s);			
		} catch (Exception e) {
			log.error("更新异常");
			ActiveUser opuser = getUser(request);//获取操作用户
			OptRecord s = new OptClass().recordabnormality(opuser,"用户管理报告权限编辑异常");
			ioptRecordService.insert(s);
			standardData.setReturnCode(CodeMsg.CODE_EXCEPTION);
			standardData.setReturnMessage(CodeMsg.MSG_EXCEPTION);
		}
		standardData.setReturnCode(CodeMsg.CODE_OK);
		standardData.setReturnMessage(CodeMsg.MSG_OK);
		return JsonUtils.toString(standardData, "yyyy-MM-dd HH:mm:ss");
	}
}
